<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考试结果 - 学生端</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
        }

        .page-header {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            text-align: center;
            position: relative;
        }

        .header-actions {
            position: absolute;
            top: 20px;
            right: 20px;
            display: flex;
            gap: 10px;
        }

        .header-actions .btn-action {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
            padding: 8px 16px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 14px;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
        }

        .header-actions .btn-action:hover {
            background: rgba(255, 255, 255, 0.3);
            border-color: rgba(255, 255, 255, 0.5);
            transform: translateY(-2px);
        }

        .back-to-top {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            font-size: 20px;
            box-shadow: 0 4px 15px rgba(0, 123, 255, 0.3);
            transition: all 0.3s ease;
            z-index: 1000;
            display: none;
        }

        .back-to-top:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(0, 123, 255, 0.4);
        }

        .back-to-top.show {
            display: block;
        }

        .page-title {
            font-size: 2.5em;
            margin: 0;
            font-weight: 300;
        }

        .page-subtitle {
            font-size: 1.1em;
            margin: 10px 0 0 0;
            opacity: 0.9;
        }

        .result-summary {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            text-align: center;
        }

        .score-display {
            font-size: 4em;
            font-weight: bold;
            margin-bottom: 20px;
        }

        .score-excellent {
            color: #28a745;
        }

        .score-good {
            color: #17a2b8;
        }

        .score-average {
            color: #ffc107;
        }

        .score-poor {
            color: #dc3545;
        }

        .score-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 20px;
            margin-top: 30px;
        }

        .score-item {
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
            text-align: center;
        }

        .score-number {
            font-size: 2em;
            font-weight: bold;
            color: #28a745;
            margin-bottom: 10px;
        }

        .score-label {
            color: #666;
            font-size: 0.9em;
        }

        .exam-info {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
        }

        .info-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .info-icon {
            font-size: 1.5em;
        }

        .info-content {
            flex: 1;
        }

        .info-label {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 5px;
        }

        .info-value {
            font-size: 1.1em;
            font-weight: 600;
            color: #333;
        }

        .answer-details {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .section-title {
            font-size: 1.5em;
            font-weight: 600;
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f0f0f0;
        }

        .question-item {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            border-left: 4px solid #e0e0e0;
        }

        .question-item.correct {
            border-left-color: #28a745;
            background: #f8fff8;
        }

        .question-item.incorrect {
            border-left-color: #dc3545;
            background: #fff8f8;
        }

        .question-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .question-header-left {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .question-type-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 12px;
            border-radius: 16px;
            font-size: 12px;
            font-weight: 600;
        }

        .question-type-badge.type-1 {
            background: #e3f2fd;
            color: #1976d2;
            border: 1px solid #2196f3;
        }

        .question-type-badge.type-2 {
            background: #f3e5f5;
            color: #7b1fa2;
            border: 1px solid #9c27b0;
        }

        .question-type-badge.type-3 {
            background: #e8f5e8;
            color: #388e3c;
            border: 1px solid #4caf50;
        }

        .question-number {
            background: #667eea;
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8em;
            font-weight: 600;
        }

        .question-status {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8em;
            font-weight: 500;
        }

        .status-correct {
            background: #d4edda;
            color: #155724;
        }

        .status-incorrect {
            background: #f8d7da;
            color: #721c24;
        }

        .question-content {
            font-size: 1.1em;
            line-height: 1.6;
            color: #333;
            margin-bottom: 15px;
            font-weight: 500;
        }

        .options-container {
            display: grid;
            gap: 10px;
            margin-bottom: 15px;
        }

        .option-item {
            display: flex;
            align-items: center;
            padding: 10px 15px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            background: white;
        }

        .option-item.correct {
            background: #d4edda;
            border-color: #28a745;
        }

        .option-item.selected {
            background: #cce5ff;
            border-color: #17a2b8;
        }

        .option-item.selected.incorrect {
            background: #f8d7da;
            border-color: #dc3545;
        }

        .option-item.multiple-choice.correct {
            background: #d4edda;
            border-color: #28a745;
        }

        .option-item.multiple-choice.selected {
            background: #cce5ff;
            border-color: #17a2b8;
        }

        .option-item.multiple-choice.selected.incorrect {
            background: #f8d7da;
            border-color: #dc3545;
        }

        .option-label {
            background: #f0f0f0;
            color: #333;
            width: 25px;
            height: 25px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            margin-right: 12px;
            font-size: 0.9em;
        }

        .option-item.correct .option-label {
            background: #28a745;
            color: white;
        }

        .option-item.selected .option-label {
            background: #17a2b8;
            color: white;
        }

        .option-item.selected.incorrect .option-label {
            background: #dc3545;
            color: white;
        }

        .option-text {
            flex: 1;
            font-size: 1em;
        }

        .answer-explanation {
            margin-top: 15px;
            padding: 15px;
            background: #e9ecef;
            border-radius: 8px;
            font-size: 0.9em;
            color: #666;
        }

        .action-buttons {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-top: 30px;
        }

        .btn-action {
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1em;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-action:hover {
            transform: translateY(-2px);
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }

        .empty-icon {
            font-size: 4em;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .empty-title {
            font-size: 1.5em;
            margin-bottom: 10px;
            color: #333;
        }

        .empty-description {
            font-size: 1em;
            line-height: 1.5;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .loading-spinner {
            display: inline-block;
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #28a745;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar">
        <div class="container-fluid">
            <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                <a href="index.html" class="navbar-brand">
                    📚 局域网视频学习系统
                </a>
                <div style="display: flex; align-items: center; gap: 20px;">
                    <a href="index.html" style="color: var(--neutral-dark); text-decoration: none;">
                        🏠 首页
                    </a>
                    <a href="favorites.html" style="color: var(--neutral-dark); text-decoration: none;">
                        ❤️ 我的收藏
                    </a>
                    <a href="playlists.html" style="color: var(--neutral-dark); text-decoration: none;">
                        📋 播放列表
                    </a>
                    <a href="exams.html" style="color: var(--neutral-dark); text-decoration: none;">
                        📝 考试中心
                    </a>
                    <a href="profile.html" style="color: var(--neutral-dark); text-decoration: none;">
                        👤 个人资料
                    </a>
                    <span style="color: var(--neutral-dark);">
                        <span data-user-name>学生</span>
                    </span>
                    <button onclick="logout()" class="logout-btn">
                        退出登录
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="page-header">
            <div class="header-actions">
                <a href="exams.html" class="btn-action">返回考试列表</a>
                <a href="exam-records.html" class="btn-action">查看所有记录</a>
            </div>
            <h1 class="page-title">📊 考试结果</h1>
            <p class="page-subtitle" id="examTitle">查看考试详细结果</p>
        </div>

        <div id="loadingState" class="loading">
            <div class="loading-spinner"></div>
            <p>正在加载考试结果...</p>
        </div>

        <div id="resultContent" style="display: none;">
            <!-- 成绩摘要 -->
            <div class="result-summary">
                <div class="score-display" id="scoreDisplay">0</div>
                <h3 id="scoreText">考试完成</h3>
                <div class="score-details">
                    <div class="score-item">
                        <div class="score-number" id="correctCount">0</div>
                        <div class="score-label">答对题数</div>
                    </div>
                    <div class="score-item">
                        <div class="score-number" id="totalCount">0</div>
                        <div class="score-label">总题数</div>
                    </div>
                    <div class="score-item">
                        <div class="score-number" id="percentage">0%</div>
                        <div class="score-label">正确率</div>
                    </div>
                    <div class="score-item">
                        <div class="score-number" id="timeUsed">0</div>
                        <div class="score-label">用时(分钟)</div>
                    </div>
                </div>
            </div>

            <!-- 考试信息 -->
            <div class="exam-info">
                <h3 class="section-title">考试信息</h3>
                <div class="info-grid">
                    <div class="info-item">
                        <div class="info-icon">📝</div>
                        <div class="info-content">
                            <div class="info-label">考试标题</div>
                            <div class="info-value" id="examTitleInfo">未知</div>
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-icon">👨‍🏫</div>
                        <div class="info-content">
                            <div class="info-label">出题老师</div>
                            <div class="info-value" id="teacherName">未知</div>
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-icon">⏱️</div>
                        <div class="info-content">
                            <div class="info-label">考试时长</div>
                            <div class="info-value" id="timeLimit">0 分钟</div>
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-icon">📅</div>
                        <div class="info-content">
                            <div class="info-label">完成时间</div>
                            <div class="info-value" id="completedTime">未知</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 答题详情 -->
            <div class="answer-details">
                <h3 class="section-title">答题详情</h3>
                <div id="answerList">
                    <!-- 答题详情将在这里动态生成 -->
                </div>
            </div>

        </div>

        <div id="emptyState" class="empty-state" style="display: none;">
            <div class="empty-icon">📊</div>
            <h3 class="empty-title">暂无结果</h3>
            <p class="empty-description">没有找到考试结果信息</p>
        </div>
    </div>

    <!-- 回到顶部按钮 -->
    <button class="back-to-top" onclick="scrollToTop()" title="回到顶部">
        ↑
    </button>

    <script src="../js/common.js"></script>
    <script>
        let examRecord = null;
        let examAnswers = [];
        let examInfo = null;
        let examStatistics = null;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', async function() {
            const authSuccess = await checkAuth();
            if (authSuccess) {
                await loadExamResult();
            }
            initBackToTop();
        });

        // 检查用户认证状态
        async function checkAuth() {
            // 确保用户信息已初始化
            await UserManager.init();
            const user = UserManager.getCurrentUser();
            if (!user || user.role !== 2) {
                Message.error('请先登录学生账号');
                setTimeout(() => {
                    window.location.href = '../login.html';
                }, 1500);
                return false; // 返回false表示认证失败
            }
            // 更新用户信息显示
            const userNameElement = document.querySelector('[data-user-name]');
            if (userNameElement) {
                userNameElement.textContent = user.name;
            }
            return true; // 返回true表示认证成功
        }

        // 加载考试结果
        async function loadExamResult() {
            const urlParams = new URLSearchParams(window.location.search);
            const examId = urlParams.get('examId');
            
            if (!examId) {
                Message.error('考试ID不存在');
                setTimeout(() => {
                    window.location.href = 'exams.html';
                }, 1500);
                return;
            }

            try {
                console.log('开始加载考试结果，examId:', examId);
                // 加载考试记录
                const recordResponse = await API.get(`/exam/answer-detail/${examId}`);
                console.log('考试记录API响应:', recordResponse);
                
                if (recordResponse.success) {
                    examRecord = recordResponse.record;
                    examAnswers = recordResponse.answers;
                    examStatistics = recordResponse.statistics; // 保存统计信息
                    
                    console.log('考试记录数据:', {
                        record: examRecord,
                        answers: examAnswers,
                        statistics: examStatistics
                    });
                    
                    // 加载考试信息
                    const examResponse = await API.get(`/exam/${examId}`);
                    console.log('考试信息API响应:', examResponse);
                    
                    if (examResponse.success) {
                        examInfo = examResponse.exam;
                    }
                    
                    renderResult();
                } else {
                    console.error('加载考试结果失败:', recordResponse.message);
                    Message.error(recordResponse.message || '加载考试结果失败');
                    showEmptyState();
                }
            } catch (error) {
                console.error('加载考试结果失败:', error);
                Message.error('加载考试结果失败，请稍后重试');
                showEmptyState();
            }
        }

        // 渲染结果
        function renderResult() {
            if (!examRecord) {
                showEmptyState();
                return;
            }

            // 隐藏加载状态
            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('resultContent').style.display = 'block';

            // 更新页面标题
            if (examInfo) {
                document.getElementById('examTitle').textContent = examInfo.title;
                document.getElementById('examTitleInfo').textContent = examInfo.title;
                document.getElementById('teacherName').textContent = examInfo.teacherName || '未知老师';
                document.getElementById('timeLimit').textContent = `${examInfo.timeLimit || 0} 分钟`;
            }

            // 使用新的统计信息（基于学生实际回答的题目）
            let correctCount, totalCount, percentage;
            
            if (examStatistics) {
                // 使用后端计算的新统计信息
                correctCount = examStatistics.correctCount || 0;
                totalCount = examStatistics.totalAnswered || 0;
                percentage = Math.round(examStatistics.accuracy || 0);
                console.log('使用新的统计信息:', examStatistics);
            } else {
                // 回退到原有逻辑
                correctCount = examRecord.score || 0;
                totalCount = examRecord.totalQuestions || 0;
                percentage = totalCount > 0 ? Math.round((correctCount / totalCount) * 100) : 0;
                console.log('使用原有统计信息');
            }
            
            const timeUsed = examRecord.examTime ? calculateTimeUsed(examRecord.examTime) : 0;

            // 更新成绩显示
            document.getElementById('scoreDisplay').textContent = correctCount;
            document.getElementById('scoreDisplay').className = `score-display ${getScoreClass(percentage)}`;
            document.getElementById('scoreText').textContent = getScoreText(percentage);
            document.getElementById('correctCount').textContent = correctCount;
            document.getElementById('totalCount').textContent = totalCount;
            document.getElementById('percentage').textContent = `${percentage}%`;
            document.getElementById('timeUsed').textContent = timeUsed;
            document.getElementById('completedTime').textContent = formatDate(examRecord.examTime);
            
            console.log('统计信息更新:', {
                correctCount,
                totalCount,
                percentage,
                timeUsed
            });

            // 渲染答题详情
            renderAnswerDetails();
        }

        // 获取成绩样式类
        function getScoreClass(percentage) {
            if (percentage >= 90) return 'score-excellent';
            if (percentage >= 80) return 'score-good';
            if (percentage >= 60) return 'score-average';
            return 'score-poor';
        }

        // 获取成绩文本
        function getScoreText(percentage) {
            if (percentage >= 90) return '优秀！';
            if (percentage >= 80) return '良好！';
            if (percentage >= 60) return '及格';
            return '需要努力';
        }

        // 计算用时
        function calculateTimeUsed(examTime) {
            // 这里可以根据实际需要计算用时
            // 暂时返回0，实际应该根据开始时间和结束时间计算
            return 0;
        }

        // 渲染答题详情
        function renderAnswerDetails() {
            const answerList = document.getElementById('answerList');
            
            if (examAnswers.length === 0) {
                answerList.innerHTML = '<p>暂无答题详情</p>';
                return;
            }

            answerList.innerHTML = examAnswers.map((answer, index) => {
                const isCorrect = answer.studentAnswer === answer.correctAnswer;
                const statusClass = isCorrect ? 'correct' : 'incorrect';
                const statusText = isCorrect ? '正确' : '错误';

                const questionType = answer.questionType || 1;
                const typeText = getTypeText(questionType);
                const typeIcon = getTypeIcon(questionType);

                return `
                    <div class="question-item ${statusClass}">
                        <div class="question-header">
                            <div class="question-header-left">
                                <span class="question-number">第 ${index + 1} 题</span>
                                <span class="question-type-badge type-${questionType}">
                                    ${typeIcon} ${typeText}
                                </span>
                            </div>
                            <span class="question-status status-${statusClass}">${statusText}</span>
                        </div>
                        <div class="question-content">${answer.questionContent || '题目内容'}</div>
                        <div class="options-container">
                            ${renderQuestionOptions(answer, answer.studentAnswer, answer.correctAnswer)}
                        </div>
                        <div class="answer-explanation">
                            <strong>您的答案：</strong>${answer.studentAnswer || '未作答'}<br>
                            <strong>正确答案：</strong>${answer.correctAnswer}
                        </div>
                    </div>
                `;
            }).join('');
        }

        // 获取题型文本
        function getTypeText(type) {
            switch (type) {
                case 1: return '单选题';
                case 2: return '多选题';
                case 3: return '判断题';
                default: return '单选题';
            }
        }

        // 获取题型图标
        function getTypeIcon(type) {
            switch (type) {
                case 1: return '🔘';
                case 2: return '☑️';
                case 3: return '✅';
                default: return '🔘';
            }
        }

        // 渲染题目选项
        function renderQuestionOptions(answer, studentAnswer, correctAnswer) {
            if (!answer) return '';

            // 从答案中获取题目类型，如果没有则默认为单选题
            const questionType = answer.questionType || 1;

            if (questionType === 3) {
                // 判断题
                const options = [
                    { key: 'T', value: '正确', icon: '✓' },
                    { key: 'F', value: '错误', icon: '✗' }
                ];

                return options.map(option => {
                    let optionClass = 'option-item';
                    if (option.key === correctAnswer) {
                        optionClass += ' correct';
                    }
                    if (option.key === studentAnswer) {
                        optionClass += ' selected';
                        if (option.key !== correctAnswer) {
                            optionClass += ' incorrect';
                        }
                    }

                    return `
                        <div class="${optionClass}">
                            <div class="option-label">${option.icon}</div>
                            <div class="option-text">${option.value}</div>
                        </div>
                    `;
                }).join('');
            } else if (questionType === 2) {
                // 多选题
                const options = [
                    { key: 'A', value: answer.optionA },
                    { key: 'B', value: answer.optionB },
                    { key: 'C', value: answer.optionC },
                    { key: 'D', value: answer.optionD }
                ].filter(opt => opt.value); // 只显示有内容的选项

                return options.map(option => {
                    let optionClass = 'option-item multiple-choice';
                    
                    // 检查是否在正确答案中
                    if (correctAnswer && correctAnswer.includes(option.key)) {
                        optionClass += ' correct';
                    }
                    
                    // 检查是否在学生答案中
                    if (studentAnswer && studentAnswer.includes(option.key)) {
                        optionClass += ' selected';
                        if (!correctAnswer || !correctAnswer.includes(option.key)) {
                            optionClass += ' incorrect';
                        }
                    }

                    return `
                        <div class="${optionClass}">
                            <div class="option-label">${option.key}</div>
                            <div class="option-text">${option.value}</div>
                        </div>
                    `;
                }).join('');
            } else {
                // 单选题
                const options = [
                    { key: 'A', value: answer.optionA },
                    { key: 'B', value: answer.optionB },
                    { key: 'C', value: answer.optionC },
                    { key: 'D', value: answer.optionD }
                ].filter(opt => opt.value); // 只显示有内容的选项

                return options.map(option => {
                    let optionClass = 'option-item';
                    if (option.key === correctAnswer) {
                        optionClass += ' correct';
                    }
                    if (option.key === studentAnswer) {
                        optionClass += ' selected';
                        if (option.key !== correctAnswer) {
                            optionClass += ' incorrect';
                        }
                    }

                    return `
                        <div class="${optionClass}">
                            <div class="option-label">${option.key}</div>
                            <div class="option-text">${option.value}</div>
                        </div>
                    `;
                }).join('');
            }
        }

        // 显示空状态
        function showEmptyState() {
            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('resultContent').style.display = 'none';
            document.getElementById('emptyState').style.display = 'block';
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '未知';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 初始化回到顶部按钮
        function initBackToTop() {
            const backToTopBtn = document.querySelector('.back-to-top');
            
            // 监听滚动事件
            window.addEventListener('scroll', function() {
                if (window.pageYOffset > 300) {
                    backToTopBtn.classList.add('show');
                } else {
                    backToTopBtn.classList.remove('show');
                }
            });
        }

        // 回到顶部功能
        function scrollToTop() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        }

        // 退出登录
        async function logout() {
            if (confirm('确定要退出登录吗？')) {
                try {
                    UserManager.logout();
                    window.location.href = '../login.html';
                } catch (error) {
                    console.error('退出登录失败:', error);
                    Message.error('退出登录失败');
                }
            }
        }
    </script>
</body>
</html>
